<?php
class M_school_settings extends MY_Model {
	
	private $__table = 'school_settings';
	
	public function get_all_school_setting($id='')
	{
		$query = $this->db->limit(1)->get($this->__table);
		return $query->num_rows() >= 1 ? $query->result() : FALSE;
	}
	
	public function check_online_status()
	{
		$sql = "SELECT online_student_portal as status
				FROM system_settings
				LIMIT 1";
		$query = $this->db->query($sql);
		return $query->num_rows() >=1 ? $query->row() : FALSE;
	}

	public function get_custom_message($type)
	{
		$sql = 'SELECT id,type,message 
				FROM system_custom_message scm
				WHERE type = "'.$type.'"
				LIMIT 1';
				
		$q = $this->db->query($sql);
		
		return $q->num_rows() >= 1 ? $q->row() : FALSE;
	}
	
	public function check_registration()
	{
		$q = $this->db->select('old_enrollment')->limit(1)->get('system_settings');
		
		
		if($q->num_rows() >= 1 )
		{
			$r = $q->row();
			return $r->old_enrollment == 1 ? 'on' : 'off';
		}else{
			log_message('error','Unable to get old_enrollment settings on system_settings table.');
			return 'off';
		}
	}
	
	private function nxtdate($year)
	{
		return (new DateTime)->createFromFormat('Y',$year)->modify('+1 year')->format('Y');
	}
	
	
	public function get_next_school_year()
	{
	
		$current_sy_from = $this->c_sy->sy_from;	// current academic year from 
		$current_sy_to = $this->c_sy->sy_to;		// current academic year to
		$id = $this->c_sy->id;						// current sy id
		$current_sy_to_nxt = $this->nxtdate($current_sy_to);

		$current_year = date('Y',time());							// current year -2013
		$current_year_nxt = $this->nxtdate($current_sy_from);			// current year next -2014 
		$current_year_nxtnxt = $this->nxtdate($current_year_nxt);	// current year next next -2015		
		
		//check if current academic year did not go back to last year
		if($current_year < $current_sy_from)
		{
			//if current school year is correct and alligned with the current year
			if($current_year_nxt == $current_sy_from AND $current_sy_to == $current_year_nxtnxt)
			{
				$v_return['sy_id'] = $id;
				$v_return['sy_yr'] = $current_sy_to.' - '.$current_sy_to_nxt;
				$v_return['sy_yr_from'] = $current_sy_to;
				$v_return['sy_yr_to'] = $current_sy_to_nxt;

			}else
			{
				$q = $this->db->where('sy_from',$current_sy_to)
								->where('sy_to',$current_sy_to_nxt)
								->limit(1)
								->get('school_years');
				
				if($q->num_rows() >= 1)
				{
					$d = $q->row();

					$v_return['sy_id'] = $d->id;
					$v_return['sy_yr'] = $current_sy_to.' - '.$current_sy_to_nxt;
					$v_return['sy_yr_from'] = $current_sy_to;
					$v_return['sy_yr_to'] = $current_sy_to_nxt;
				}else{
					$v_return['sy_id'] = FALSE;
					$v_return['sy_yr'] = $current_sy_to.' - '.$current_sy_to_nxt;
					$v_return['sy_yr_from'] = $current_sy_to;
					$v_return['sy_yr_to'] = $current_sy_to_nxt;
				}
			}
		}else{
			$v_return['sy_id'] = FALSE;
			$v_return['sy_yr'] = ' {Invalid Year} ';
		}
		
		return (object)$v_return;
	}
}
?>